/********************************************************************
        File :			Demultiplexor.cpp
        Creation date :	2010/6/27
		
        License :			Copyright 2010 Ahmed Charfeddine, http://www.pushframework.com

                                   Licensed under the Apache License, Version 2.0 (the "License");
                                   you may not use this file except in compliance with the License.
                                   You may obtain a copy of the License at
				
                                           http://www.apache.org/licenses/LICENSE-2.0
				
                                   Unless required by applicable law or agreed to in writing, software
                                   distributed under the License is distributed on an "AS IS" BASIS,
                                   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                                   See the License for the specific language governing permissions and
                                   limitations under the License.
	
	
 *********************************************************************/
#include "StdAfx.h"
#include "Demultiplexor.h"

#include "ServerImpl.h"
#include "Dispatcher.h"
#include "Channel.h"
#include "IOCPQueue.h"
#include "../include/Server.h"

namespace PushFramework {

    Demultiplexor::Demultiplexor(ServerImpl *pServerImpl) {
        this->pServerImpl = pServerImpl;
    }

    Demultiplexor::~Demultiplexor(void) {
    }

    bool Demultiplexor::start() {
        stopWorking = false;

        int nThreads = pServerImpl->getWorkerCount();
        for (int i = 0; i < 2; i++) {
            pthread_t thread;
            pthread_create(&thread, NULL, KerIOCPWorkerProc, (void*) this);
            workersThreadsVect.push_back(thread);
        }
        return true;

    }

    void Demultiplexor::stop() {
        stopWorking = true;
        cout << "waiting for worker threads to stop" << endl;
        for (int i = 0; i < workersThreadsVect.size(); i++) {
            pthread_t hThread = workersThreadsVect.at(i);
            pthread_join(hThread, NULL);
        }

        cout << "stopWorkers ok" << endl;
    }

    void* Demultiplexor::KerIOCPWorkerProc(void* WorkContext) {
        Demultiplexor* pThis = reinterpret_cast<Demultiplexor*> (WorkContext);

        pThis->proc();

        return 0;
    }

    void Demultiplexor::proc() {
        //CLoggingFacilities::doLoggingByArgList("Worker %x started..",::GetCurrentThreadId());
        void* perThreadCtx = pServerImpl->getFacade()->workerThreadBegin();


        CChannel *pPerSocketContext = NULL;


        int epollArraySize = 64;
        struct epoll_event epoll_events[64];


        while (!stopWorking) {
            int rval = pServerImpl->getIOCPQueue()->GetQueuedEvent(epoll_events, epollArraySize);

            if (rval == 0) {
                //cout << "timeout happened" << endl;
                continue;
            }

            if (rval < 0) {
                cout << "FATAL" << endl;
                return;
            }

            //Start handling events :

            for (int i = 0; i < rval; i++) {
                //
                uint32_t events = epoll_events[i].events;
                int fd = epoll_events[i].data.fd;
                pPerSocketContext = (CChannel *) epoll_events[i].data.ptr;


                if (events & EPOLLERR) {
                    shutdown(fd, SHUT_RDWR);
                    close(fd);
                    continue;
                }
                if (events & EPOLLHUP) {
                    shutdown(fd, SHUT_RDWR);
                    close(fd);
                    continue;
                }
                if (events & EPOLLRDHUP) {
                    shutdown(fd, SHUT_RDWR);
                    close(fd);
                    continue;
                }

                //
                if (events & EPOLLOUT) {
                    pServerImpl->getDispatcher()->OnReadyToWrite(pPerSocketContext);
                }
                if (events & EPOLLIN) {
                    pServerImpl->getDispatcher()->OnReadyToRead(pPerSocketContext);
                }

            }

        }

        pServerImpl->getFacade()->workerThreadEnd(perThreadCtx);
    }

}

